package cn.softwin.controller;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.softwin.service.UserService;
import cn.softwin.service.impl.UserServiceImpl;



/**
 * Servlet implementation class SubServlet
 */
@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		doGet(request, response);
		request.setCharacterEncoding("utf-8");
//		response.setContentType("text/html,charset=utf-8");
		String name = request.getParameter("txtName");
		String pass = request.getParameter("txtPwd");
		String syzm = request.getParameter("txtcode");

		Cookie[] cs = request.getCookies();

		if(cs!=null) {
			String yzm = (String)request.getSession().getAttribute("yzm");
			if(!yzm.equals(syzm)) {
				Cookie c = new Cookie("login", "验证码错误");
				response.addCookie(c);
				response.sendRedirect("login.jsp");
			}else{
				UserService userServiceImpl = new UserServiceImpl();
				boolean b = userServiceImpl.selectuser(name, pass);
				if(!b) {
					Cookie c = new Cookie("login", "密码或账号错误");
					response.addCookie(c);
					response.sendRedirect("login.jsp");
				}else {
					HttpSession session = request.getSession();
					session.setAttribute("user", "user");
					Cookie c = new Cookie("login", "登录成功");
					response.addCookie(c);
					request .getRequestDispatcher("index.jsp").forward(request, response);
				}
			}
			
		}
	}

}
